package com.lamda.zhekou.dao.impl;


import com.lamda.zhekou.dao.UserDao;
import com.lamda.zhekou.manager.PageModel;
import com.lamda.zhekou.model.User;
import com.lamda.zhekou.vo.UserVpsSelectVo;
import org.springframework.stereotype.Repository;

import javax.persistence.Query;
import java.util.List;

/**
 * Created by MJiao on 15/8/13.
 */
@Repository
public class UserDaoImpl extends GenericDaoImpl<User> implements UserDao {

    @Override
    public PageModel<User> paging(int pageNo, int pageSize) {
        return this.paging(pageNo, pageSize, true);
    }

    @Override
    public List<User> getUsersByFyEmailFilter(String keyWord) {
        String qlString ="select e from User e where e.email like :keyWord";
        return   this.entityManager.createQuery(qlString).setParameter("keyWord", "%" + keyWord + "%").getResultList();
    }

    @Override
    public List<User> findAllAdmins() {
        String qlString = "select e from User e where e.role=1";
        return this.entityManager.createQuery(qlString).getResultList();
    }

    @Override
    public List<User> findAllCommonUser() {
        String qlString = "select e from User e where e.role=0";
        return this.entityManager.createQuery(qlString).getResultList();
    }

    /**
     * 分页查询
     *
     * @param pageNo
     * @param pageSize
     * @param asc      是否为升序查询
     * @return
     */
    @Override
    public PageModel<User> paging(int pageNo, int pageSize, boolean asc) {


        PageModel<User> pageModel = new PageModel<>();

        int start = (pageNo - 1) * pageSize;
        //获取总行数
        long count = this.selectCount();
        String qlString = new StringBuilder("select e from User e order by e.id ") .append(asc ? "asc " : "desc").toString();
        Query query = this.entityManager.createQuery(qlString);
        // 判断分页
        if (start < count && pageSize > 0) {
            query.setFirstResult(start);
            query.setMaxResults(pageSize);
        }
        List<User> resultList = query.getResultList();

        pageModel.setTotalRecords((int) count);
        pageModel.setPageNo(pageNo);
        pageModel.setPageSize(pageSize);
        pageModel.setList(resultList);

        return pageModel;
    }


}
